package cn.ycc1.boot3video.video;

import lombok.Data;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ParallelHlsGeneratorBak {

    private static final int THREAD_POOL_SIZE = 3;

    @Data
    public static class EncodingTask implements Runnable {
        private String inputPath;
        private String outputDir;
        private String quality;
        private int bandwidth;
        private String resolution;

        public EncodingTask(String inputPath, String outputDir, String quality,
                            int bandwidth, String resolution) {
            this.inputPath = inputPath;
            this.outputDir = outputDir;
            this.quality = quality;
            this.bandwidth = bandwidth;
            this.resolution = resolution;
        }

        @Override
        public void run() {
            try {
                String[] commands = {
                        "ffmpeg", "-i", inputPath,
                        "-c:v", "libx264", "-c:a", "aac",
                        "-b:v", String.valueOf(bandwidth) + "k",
                        "-maxrate", String.valueOf((int)(bandwidth * 1.07)) + "k",
                        "-bufsize", String.valueOf((int)(bandwidth * 1.5)) + "k",
                        "-b:a", getAudioBitrate(bandwidth) + "k",
                        "-vf", "scale=" + resolution,
                        "-hls_time", "4",
                        "-hls_playlist_type", "vod",
                        "-hls_segment_filename",
                        outputDir + "/" + quality + "_%03d.ts",
                        outputDir + "/" + quality + ".m3u8"
                };

                Process process = Runtime.getRuntime().exec(commands);
                int exitCode = process.waitFor();

                if (exitCode == 0) {
                    System.out.println(quality + " encoding completed");
                } else {
                    System.err.println(quality + " encoding failed");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private String getAudioBitrate(int videoBitrate) {
            if (videoBitrate >= 2000) return "128";
            else if (videoBitrate >= 1000) return "96";
            else return "64";
        }
    }

    public static boolean generateMultiQualityHls(String inputPath, String outputDir) {
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

        try {
            // 定义不同清晰度的配置
            EncodingTask[] tasks = {
                    new EncodingTask(inputPath, outputDir, "1080p", 2000, "1920:1080"),
                    new EncodingTask(inputPath, outputDir, "720p", 1000, "1280:720"),
                    new EncodingTask(inputPath, outputDir, "480p", 500, "854:480")
            };

            // 提交所有任务并行执行
            Future<?>[] futures = new Future[tasks.length];
            for (int i = 0; i < tasks.length; i++) {
                futures[i] = executor.submit(tasks[i]);
            }

            // 等待所有任务完成
            for (Future<?> future : futures) {
                future.get(); // 会阻塞直到任务完成
            }

            // 生成主播放列表
            generateMasterPlaylist(outputDir);
            return true;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            executor.shutdown();
        }
    }

    private static void generateMasterPlaylist(String outputDir) {
        // 使用之前的方法生成master.m3u8
        List<VariantStreamBak> variants = Arrays.asList(
                new VariantStreamBak(
                        "1080p.m3u8", 2000000, "1920x1080", "avc1.640028,mp4a.40.2", "1080p"),
                new VariantStreamBak(
                        "720p.m3u8", 1000000, "1280x720", "avc1.64001f,mp4a.40.2", "720p"),
                new VariantStreamBak(
                        "480p.m3u8", 500000, "854x480", "avc1.64001e,mp4a.40.2", "480p")
        );

        String masterContent = HlsMasterPlaylistGenerator.generateMasterPlaylist(variants);

        try {
            HlsMasterPlaylistGenerator.saveToFile(masterContent, outputDir + "/master.m3u8");
            System.out.println("Master playlist generated");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    public static boolean generateMultiQualityHls(String inputPath, String outputDir) {
//        ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
//
//        try {
//            // 确保输出目录存在
//            java.io.File dir = new java.io.File(outputDir);
//            if (!dir.exists()) {
//                dir.mkdirs();
//            }
//
//            // 定义不同清晰度的配置
//            EncodingTask[] tasks = {
//                    new EncodingTask(inputPath, outputDir, "1080p", 2000, "1920:1080"),
//                    new EncodingTask(inputPath, outputDir, "720p", 1000, "1280:720"),
//                    new EncodingTask(inputPath, outputDir, "480p", 500, "854:480")
//            };
//
//            // 提交所有任务并行执行
//            Future<?>[] futures = new Future[tasks.length];
//            for (int i = 0; i < tasks.length; i++) {
//                futures[i] = executor.submit(tasks[i]);
//            }
//
//            // 等待所有任务完成
//            for (Future<?> future : futures) {
//                future.get(); // 会阻塞直到任务完成
//            }
//
//            // 生成主播放列表 - 使用动态生成方式
//            HlsMasterPlaylistGenerator.generateMasterPlaylist(outputDir);
//            return true;
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            return false;
//        } finally {
//            executor.shutdown();
//        }
//    }

    public static void main(String[] args) {
        boolean success = generateMultiQualityHls(
                "/path/to/input.mp4",
                "/path/to/output"
        );

        if (success) {
            System.out.println("All quality levels generated successfully");
        } else {
            System.out.println("HLS generation failed");
        }
    }
}
